import { setRightMenu } from '../menu';
import getCellName from '../../../../utils/getCellName';
import { isEditableArea } from '../command';
import { message } from 'antd';
import { WeaLocaleProvider, WeaTools } from "ecCom";
const getLabel = WeaLocaleProvider.getLabel;
import API from '../../../../apis/task';
import { each,uniqueId } from 'lodash';

export function dragFillBlock(e, info) {
    const { sheet, fillRange, fillDirection } = info;
    this.cantriggerClick = false;
    sheet.suspendPaint();
    const { row, col, colCount } = fillRange;
    const getDragCol = (table, colIndex, colSize) => {
        const dataRange = table.dataRange();
        const cols = [];
        for (let index = 0; index < colSize; index++) {
            cols.push(table.getColumnDataField(colIndex + index - dataRange.col));
        }
        return cols;
    }
    if (fillDirection === GC.Spread.Sheets.Fill.FillDirection.down) {
        const newRecords = [];
        const table = sheet.tables.find(row - 1, col);
        const tableName = table.bindingPath();
        const records = this.dataSourceInstance.getValue(tableName);
        const dataRange = table.dataRange();
        const cols = getDragCol(table, col, colCount);
        const dragRecord = records[row - dataRange.row - 1];
        const copyRecord = {};
        cols.forEach(c => {
            copyRecord[c] = dragRecord[c];
        });
        let detailIndex = 1;
        for (let index = 0; index < dataRange.rowCount; index++) {
            const currentRow = dataRange.row + index;
            if (currentRow < row) {
                newRecords.push({ ...records[index], detail_index: detailIndex++ });
            } else if (currentRow >= row) {
                if (currentRow < fillRange.row + fillRange.rowCount) {
                    newRecords.push({ ...records[index], ...copyRecord, detail_index: detailIndex++ });
                } else {
                    newRecords.push({ ...records[index], detail_index: detailIndex++ });
                }
            }
        }
        const fillSize = fillRange.row + fillRange.rowCount;
        for (let index = dataRange.row + dataRange.rowCount; index < fillSize; index++) {
            newRecords.push({ ...copyRecord, detail_index: detailIndex++ });
        }

        this.dataSourceInstance.setValue(tableName, newRecords);
        table.bindingPath(tableName);
    }
    this.calcAll(true, sheet.name());
    sheet.resumePaint();
    info.cancel = true;
    setTimeout(() => {
        this.cantriggerClick = true;
    }, 100);
}
export function ClipboardChanged(e, info) {
    const { sheet } = info;
    this.clipboardRanges = sheet.getSelections();
}
export function clipboardPasted(info) {
    const { sheetName, fromRanges = [], fromSheet, pastedRanges, clipboardText } = info;
    if (!this.readonly) {
        this.workbook.commandManager().execute({
            autoFitType: GC.Spread.Sheets.AutoFitType.cell,
            cmd: 'edc.excelView.paste',
            sheet: this.workbook.getSheetFromName(sheetName),
            sourceRange: fromRanges && fromRanges[0],
            sourceSheet: fromSheet,
            cellRange: pastedRanges && pastedRanges[0],
            value: clipboardText,
            callback: this.calcAll.bind(this, false, sheetName)
        });
    }
}

export function cellClick(e, data) {
    if (this.readonly) {
        return;
    }
    const { sheet, row, col } = data;
    const range = sheet.getCell(row, col);
    const cellType = range.cellType();
    if (cellType && cellType.viewAttr == 1) {
        return;
    }
    if (cellType instanceof WeaDatePickerCellType) {
        const host = this.workbook.getHost();
        const offset = jQuery(host).offset();
        const rect = sheet.getCellRect(row, col);
        cellType.showDatePicker(rect.x + offset.left, rect.y + offset.top, range);
    } else if (cellType instanceof WeaTimePickerCellType) {
        const host = this.workbook.getHost();
        const offset = jQuery(host).offset();
        const rect = sheet.getCellRect(row, col);
        cellType.showTimePicker(rect.x + offset.left, rect.y + offset.top, range);
    }
}

export function enterCell(e, info) {
    const { sheet, row, col } = info;
    const table = sheet.tables.find(row, col);
    if (table) {
        // 只有可编辑时才可以添加行
        if (this.canSubmit) {
            const range = sheet.getCell(row, col);
            const cellType = range.cellType();
            setRightMenu(this, true, row < table.dataRange().row, table, cellType, this.rowControl);
        } else {
            setRightMenu(this, false);
        }
        this.activeCellName = `${getCellName(row, col)}(${table.name()})`;
    } else {
        setRightMenu(this, false);
        this.activeCellName = getCellName(row, col);
    }
}

export function editStarting(e, info) {
    const { sheet, row, col } = info;
    const cellType = sheet.getCell(row, col).cellType();
    if (this.readonly) {
        info.cancel = true;
    } else if (cellType && cellType.viewAttr == 1) {
        info.cancel = true;
    } else {
        if (cellType instanceof WeaInputCellType || cellType instanceof WeaCheckboxCellType ||
            cellType instanceof WeaBrowserCellType || cellType instanceof WeaSelectCellType) {
        } else {
            info.cancel = true;
        }
    }
}

export function activeSheetChange(e, info) {
    this.workbook.suspendPaint();
    if (info.newSheet) {
        info.newSheet.setDataSource(this.dataSourceInstance);
        info.newSheet.tables.all().forEach((table, tableIndex) => {
            table.bindingPath(table.bindingPath())
        });
        if (info.newSheet.hasCalcAll) {
            this.calcAll(false, info.newSheet.name());
        } else {
            info.newSheet.hasCalcAll = true;
            this.calcAll(true, info.newSheet.name());
        }

    }
    this.workbook.resumePaint();
}

export function editEnded(e, info) {
    const { sheet, row, col, editingText } = info;

    const table = sheet.tables.find(row, col);
    if (table) {
        const { spanKeys } = table;
        const { col: startCol } = table.dataRange();
        if (spanKeys && spanKeys.length > 0) {
            spanKeys.forEach(key => {
                if (key.index + startCol === col) {
                    const span = sheet.getSpan(row, col);
                    if (span) {
                        sheet.getRange(span.row, span.col, span.rowCount, span.colCount).value(editingText);
                    }
                }
            });
        }
        //table.bindingPath(table.bindingPath());
        this.calcAll(false, sheet.name());
    }
}
const GetLength = (str) => {
    ///<summary>获得字符串实际长度，中文2，英文1</summary>
    ///<param name="str">要获得长度的字符串</param>
    var realLength = 0, len = str.length, charCode = -1;
    for (var i = 0; i < len; i++) {
        charCode = str.charCodeAt(i);
        if (charCode >= 0 && charCode <= 128)
            realLength += 1;
        else
            realLength += 2;
    }
    return realLength;
};
export function cellChanged(e, info) {

    const { propertyName, newValue, oldValue, row, col, sheet } = info;
    if (propertyName === 'value' && this.needCheck) {
        const cell = sheet.getCell(row, col);
        const cellType = cell.cellType();
        if (cellType) {
            if (cellType instanceof WeaInputCellType) {
                const { fieldType: [htmlType, type, dbtype] } = cellType;
                if (type === 'text') {
                    if (newValue) {
                        const length = parseInt(dbtype);
                        if (GetLength(`${newValue}`) > length) {
                            cell.value(oldValue);
                            message.error(`${getLabel('502997', '长度不能超过') + length}`);
                        }
                    }
                } else if (type === 'int') {
                    if (newValue) {

                        const realValue = parseInt(newValue);
                        if (isNaN(realValue)) {

                            message.error(getLabel('502998', '请输入整数'));
                            cell.value(oldValue);
                        } else {
                            if ((newValue + '').length > 11) {
                                message.error('整数最大长度为11位');
                                cell.value(oldValue);
                                return;
                            }
                            cell.value(realValue);
                        }
                    }
                } else if (type === 'float') {
                    if (newValue) {
                        const realValue = parseFloat(newValue);
                        const length = parseInt(dbtype);
                        if (isNaN(realValue)) {
                            message.error(getLabel('502999', '请输入浮点数'));
                            cell.value(oldValue);
                        } else {
                            const value = toDecimal2(newValue);
                            if (value.length > 37) {
                                message.error('浮点数整数位最大长度为34位');
                                cell.value(oldValue);
                                return;
                            }
                            cell.value(value);
                        }
                    }
                }
            } else {
                this.workbook.suspendPaint();
                const table = sheet.tables.find(row, col);
                if (table) {
                    const { spanKeys } = table;
                    const { col: startCol } = table.dataRange();
                    if (spanKeys && spanKeys.length > 0) {
                        spanKeys.forEach(key => {
                            if (key.index + startCol === col) {
                                const span = sheet.getSpan(row, col);
                                if (span) {
                                    sheet.getRange(span.row, span.col, span.rowCount, span.colCount).value(newValue);
                                }
                            }
                        });
                    }
                    //table.bindingPath(table.bindingPath());
                    this.calcAll(false, sheet.name());
                }

                this.workbook.resumePaint();
            }

            let value = "";
            if (cellType instanceof WeaBrowserCellType) {
                if (newValue && Array.isArray(newValue)) {
                    let idArr = new Array();
                    newValue.forEach((o) => {
                        idArr.push(o.id);
                    });
                    value = idArr.join(",");
                }
            } else {
                value = newValue;
            }


            // 下拉框联动逻辑
            if (cellType instanceof WeaSelectCellType && newValue != '-999') {
                const filedType = cellType.fieldType;
                if (filedType && filedType[2]) {
                    const relatedChild = filedType[2].relatedChild;
                    const datas = filedType[2].datas;


                    if (relatedChild) {
                        // 下拉框选择的值
                        const selectValue = datas.filter(r => r.selectValue == newValue)[0];
                        // 选择框有值时
                        if (selectValue && newValue) {

                            relatedChildFun(relatedChild, selectValue.childValue, newValue, cellType, sheet, row, col);
                        } else {
                            relatedChildFun(relatedChild, undefined, undefined, cellType, sheet, row, col);
                        }
                    }
                }
            }

            const table = sheet.tables.find(row, col);
            let changeFieldName = "";
            let isDetailField = "0";
            //改变字段是主表字段
            let detail_index = 0;
            if (table) {
                isDetailField = "1";
                const dataRange = table.dataRange();
                const mxColumn = table.getColumnDataField(col - dataRange.col);
                detail_index = row - dataRange.row + 1;
                const bindingPath = table.bindingPath();
                changeFieldName = bindingPath + "." + mxColumn;
            } else {
                changeFieldName = sheet.getCell(row, col).bindingPath();
            }
            const key = `\\$${changeFieldName}\\$`;
            const regExp = new RegExp(key, 'g');
            //参数为sql时需要进行编码
            const Base64 = WeaTools.Base64;
            const newfieldAssignList = this.fieldAssignList.filter(f => f.type == '1' && f.conditionInfo.search(regExp) != -1).map(fa => {
                let sql = "";
                const { id, conditionInfo } = fa;
                const conditionInfoObj = JSON.parse(conditionInfo);
                const { conditiontype, conditionsql, conditionsql2 } = conditionInfoObj;
                if (conditiontype === "1") {
                    sql = conditionsql;
                } else if (conditiontype === "2") {
                    sql = conditionsql2;
                }
                sql = sql.replace(regExp, value);
                return { id: id, sql: Base64.encode(sql) };
            });
            let dataParams = {
                ...this.params,
                isDetailField: isDetailField,
                sqls: JSON.stringify(newfieldAssignList)
            };
            if (newfieldAssignList.length > 0) {
                if (isDetailField === "1") {
                    API.getFieldAssignData(dataParams).then((result) => {
                        if (result.returnList) {
                            result.returnList.forEach((r) => {
                                const field = r.field;
                                if (field) {
                                    const paths = field.split('.');
                                    let bindingPath = "";
                                    let dfield = "";
                                    if (paths.length >= 3) {
                                        bindingPath = paths[0] + '.' + paths[1];
                                        dfield = paths[2];
                                    }
                                    const records = this.dataSourceInstance.getValue(bindingPath);
                                    const newRecords = records.map((o, key) => {
                                        if (detail_index == key + 1) {
                                            return { ...o, [dfield]: r.value };
                                        } else {
                                            return o;
                                        }
                                    });
                                    sheet.suspendPaint();
                                    this.dataSourceInstance.setValue(bindingPath, newRecords);
                                    table.bindingPath(bindingPath);
                                    sheet.resumePaint();
                                    sheet.repaint();
                                }
                            });

                        }
                    });
                } else {
                    API.getFieldAssignData(dataParams).then((result) => {
                        if (result.returnList) {
                            sheet.suspendPaint();
                            const resultData = result.returnList;
                            let bindingPathArr = [];
                            let detailData = {};
                            resultData.forEach((r) => {
                                if (r.fieldtype == "mainfield") {
                                    this.dataSourceInstance.setValue(r.field, r.value);
                                } else if (r.fieldtype == "detailfield") {
                                    const field = r.field;
                                    if (field) {
                                        const paths = field.split('.');
                                        let bindingPath = "";
                                        let dfield = "";
                                        if (paths.length >= 3) {
                                            bindingPath = paths[0] + '.' + paths[1];
                                            dfield = paths[2];
                                        }
                                        if (bindingPathArr.indexOf(bindingPath) == -1) {
                                            bindingPathArr.push(bindingPath);
                                            detailData[bindingPath] = [];
                                        }
                                        if (detailData[bindingPath]) {
                                            const detailObj = { dfield: dfield, value: r.value };
                                            detailData[bindingPath].push(detailObj);
                                        } else {
                                            detailData[bindingPath] = [];
                                        }
                                    }
                                }
                            });

                            bindingPathArr.forEach((b) => {
                                if (b && b != "") {
                                    if (detailData[b]) {
                                        const records = this.dataSourceInstance.getValue(b);
                                        let oldNum = 0;
                                        records.forEach((record) => {
                                            let isAdd = false;
                                            for (let [key, value] of Object.entries(record)) {
                                                if (key !== 'detail_index') {
                                                    if (value && value != "") {
                                                        isAdd = true;
                                                        break;
                                                    }
                                                }
                                            }
                                            //一行有一个字段不为空就计入初始行数，这个判断要在明细表加载前执行
                                            if (isAdd) {
                                                //遍历表格数据假如该行有数据则计入初始行数
                                                oldNum++;
                                            }
                                        });
                                        const detail = detailData[b];
                                        const newRecords = [];
                                        records.forEach((record, recordIndex) => {
                                            if (recordIndex < oldNum) {
                                                newRecords.push({ ...record });
                                            }
                                        })
                                        detail.forEach((field) => {
                                            if (field) {
                                                const { dfield, value: valueArr } = field;
                                                const recordsSize = records.length;
                                                const rowCount = recordsSize - oldNum;
                                                const dataCount = valueArr.length;
                                                if (rowCount <= dataCount) {
                                                    valueArr.forEach((data, dataIndex) => {
                                                        if (newRecords[dataIndex + oldNum]) {
                                                            newRecords[dataIndex + oldNum] = { ...newRecords[dataIndex + oldNum], [dfield]: data };
                                                        } else {
                                                            newRecords.push({ [dfield]: data, detail_index: dataIndex + oldNum + 1 });
                                                        }

                                                    });
                                                } else {
                                                    records.forEach((record, recordIndex) => {
                                                        if (recordIndex >= oldNum) {
                                                            if (!newRecords[recordIndex]) {
                                                                newRecords.push({ detail_index: recordIndex + 1 });
                                                            }
                                                            if (recordIndex - oldNum < dataCount) {
                                                                newRecords[recordIndex] = { ...newRecords[recordIndex], [dfield]: valueArr[recordIndex - oldNum] };
                                                            }
                                                        }
                                                    });
                                                }
                                            }
                                        })
                                        this.dataSourceInstance.setValue(b, newRecords);
                                        this.workbook.sheets.forEach(sheet => {
                                            sheet.tables.all().forEach((table, tableIndex) => {
                                                table.bindingPath(table.bindingPath())
                                            });
                                            this.calcAll(true, sheet.name());
                                        });
                                    }
                                }
                            });

                            sheet.resumePaint();
                        }
                    });
                }
            }
        }

        if (this.requiredCellName && this.requiredCellName == (row + "@" + col)) {
            if (cell.text()) {
                if (this.requiredCellBoderStyle[this.requiredCellName]) {

                    cell.setBorder(this.requiredCellBoderStyle[this.requiredCellName][0], { top: true });
                    cell.setBorder(this.requiredCellBoderStyle[this.requiredCellName][1], { right: true });
                    cell.setBorder(this.requiredCellBoderStyle[this.requiredCellName][2], { bottom: true });
                    cell.setBorder(this.requiredCellBoderStyle[this.requiredCellName][3], { left: true });
                }
                this.requiredCellName = "";
            }
        }
		
		//dataTable改造
        //记录修改的cell,拼成理想json
        const value = cell.value();
        const sheetName = sheet.name();
        const { id,table,field } = window.dataTableInstance[row] ? window.dataTableInstance[row][col] : {};
        const tableObj = sheet.tables.find(row, col);
        const tableName = table==='main'?table:tableObj.tableName().replace("detail", "detail_");
        const colObj  = tableObj?tableObj.toJSON().columns[col]:{};
        const fieldName = field?field:colObj.dataField

        window.updateJson[sheetName] = window.updateJson[sheetName]?window.updateJson[sheetName]:{};
        if (tableName === 'main') {
            window.updateJson[sheetName][fieldName] = value;
        }else{
            if (window.updateJson[sheetName][tableName]) {
                window.updateJson[sheetName][tableName].map(rowJson => { //整合row相同的单元格
                    if (rowJson.row === row) {
                        rowJson[fieldName] = value;
                    } else {
                        //判断json串中是否有该row数据 没有就新增
                        if (!check(window.updateJson[sheetName][tableName], row)) window.updateJson[sheetName][tableName].push({ row, id: id ? id : uniqueId("-"), [fieldName]: value });
                    }
                });
            } else {
                window.updateJson[sheetName][tableName] = [{ row, id: id ? id : uniqueId("-"), [fieldName]: value }];
            }
        }
        //console.log("updateJson", window.updateJson);
		
		
    }
}

function check(tableJson, row) {
    let flag = false;
    tableJson.map(rowJson => {
        if (rowJson.row === row) {
            flag = true;
        }
    })
    return flag;
}


function relatedChildFun(relatedChild, childValues, value, cellType, sheet, row, col) {

    const cvalues = childValues ? childValues.split(",") : undefined;
    const table = sheet.tables.find(row, col);
    let bindingPath = "";
    let fieldName = "";
    let istable = 0;
    if (table) {
        // 明细表
        const bindingPath = table.bindingPath();
        if (bindingPath) {
            const { col, colCount, rowCount } = table.dataRange();
            for (let i = 0; i < colCount; i++) {
                const childCell = sheet.getCell(Number(row), Number(col + i));
                const cellType = childCell.cellType();
                if (cellType && cellType.typeName == 'WeaSelectCellType' && cellType.fieldType) {
                    const fieldName = table.getColumnDataField(i);
                    if (relatedChild == fieldName) {
                        let newItems = [];
                        if (cvalues) {
                            newItems = cellType.fieldType[2].datas.filter(r =>
                                cvalues.indexOf(r.selectName) > -1
                            );
                        } else if (value) {
                        } else {
                            // 父字段没有值，子字段也不能选
                            //newItems = cellType.fieldType[2].datas;
                        }

                        console.log(newItems);
                        if (newItems.length == 0 && childCell.value()) {
                            childCell.value(undefined);
                        } else {
                            if (newItems.filter(r => r.selectValue == childCell.value()).length < 1) {
                                if(childCell.value()) {
                                    childCell.value(undefined);
                                }
                            }
                        }
                        cellType.items(newItems.map((d) => ({ text: d.selectName, value: '' + d.selectValue })));

                    }
                }
            }
        }

    } else {
        const path = sheet.getBindingPath(row, col);
        if (path) {

            //const [path, fieldName] = path.split('.');
            const { data } = sheet.toJSON();
            if (data) {
                const { dataTable } = data;
                if (dataTable) {
                    each(dataTable, (o, rowIndex) => {
                        each(o, (obj, colIndex) => {
                            const bindingPath = sheet.getBindingPath(rowIndex, colIndex);
                            if (bindingPath) {

                                const [sheetName, fieldName] = bindingPath.split('.');
                                if (relatedChild == fieldName) {
                                    const childCell = sheet.getCell(Number(rowIndex), Number(colIndex));
                                    const cellType = childCell.cellType();
                                    if (cellType && cellType.typeName == 'WeaSelectCellType' && cellType.fieldType) {

                                        let newItems = [];
                                        if (cvalues) {
                                            newItems = cellType.fieldType[2].datas.filter(r =>
                                                cvalues.indexOf(r.selectName) > -1
                                            );
                                        } else if (value) {
                                        } else {
                                            //newItems = cellType.fieldType[2].datas;
                                        }
                                        if (newItems.length == 0 && childCell.value()) {
                                            childCell.value(undefined);
                                        } else {
                                            if (newItems.filter(r => r.selectValue == childCell.value()).length < 1) {
                                                if(childCell.value()) {
                                                    childCell.value(undefined);
                                                }
                                            }
                                        }
                                        cellType.items(newItems.map((d) => ({ text: d.selectName, value: '' + d.selectValue })));
                                    }
                                }

                            }

                        });
                    });

                }
            }
        }
    }
}

//强制保留2位小数，如：2，会在2后面补上00.即2.00 
function toDecimal2(s) {
    let pre = ""
    if (s.indexOf("-") == 0) {
        pre = "-"
    }
    s = s.replace(/[^\d.]/g, "");
    let rs = s.indexOf('.');

    if (rs < 0) {
        rs = s.length;
        s += '.00';
    } else if (s.length > rs + 2) {
        s = s.substring(0, rs + 3)
    }

    while (s.length <= rs + 2) {
        s += '0';
    }
    return pre + s;
}
